import {
  acceptDeviceShare,
  createDeviceShareRecord,
  fetchMyShareDevices,
  fetchShareToMineDevices,
  IMyShareDevice,
  ISharedDevice
} from '@/services/share';
import i18n from 'i18n-js';
import { makeAutoObservable } from 'mobx';
import Toast from '@/utils/Toast';
import deviceListModel from './deviceList';
import homesModel from './homes';

type CreateDeviceShareRecordParam = Omit<GetFnFirstParam<typeof createDeviceShareRecord>, 'shareDevices'>;

class DeviceShare {
  private shareId = '';
  private selectedDevices: IDevice[] = [];

  list: IMyShareDevice[] = [];
  receiveList: ISharedDevice[] = [];

  constructor() {
    makeAutoObservable(this);
  }

  init() {
    // this.fetchList();
    // this.fetchReceiveList();
  }

  async fetchList() {
    // const res = await fetchMyShareDevices();
    // if (res.success && res.data) {
    //   this.list = res.data;
    // }
  }

  async fetchReceiveList() {
    // const res = await fetchShareToMineDevices();
    // if (res.success && res.data) {
    //   this.receiveList = res.data;
    // }
  }

  updateShareId(id: string) {
    this.shareId = id;
  }

  checkDeviceShare() {
    if (!this.shareId) {
      return;
    }
    this.acceptShare(this.shareId);
    this.shareId = '';
  }

  parseAcceptShareMessage(res: { code: number; message?: string }) {
    if ([2000058, 2000057].includes(res.code)) {
      return i18n.t('SHARE_FAILURE');
    }
    if (res.code === 2000066) {
      return i18n.t('YOU_ALREADY_SHARE_THIS_DEVICE_TIP');
    }
    return res.message || i18n.t('ACCEPT_SHARE_FAIL');
  }

  async acceptShare(id: string) {
    Toast.loading('');
    const res = await acceptDeviceShare(id);
    if (res.success) {
      Toast.success(i18n.t('ACCEPT_SHARE_SUCCESS'));
    } else {
      Toast.error(this.parseAcceptShareMessage(res as any));
    }
    if (res.success) {
      this.fetchReceiveList();
      setTimeout(() => {
        homesModel.initHomes();
        deviceListModel.getDeviceList(true);
      }, 100);
    }
    return res;
  }

  isShareToMeDevice = (device: IDevice) => {
    return device.deviceSourceType === 2; // 2代表是被分享的设备
  }

  setSelectedDevices(devices: IDevice[]) {
    this.selectedDevices = devices;
  }

  getSelectedDevices() {
    return this.selectedDevices
  }

  createDeviceShareRecord(params: CreateDeviceShareRecordParam = {}) {
    return createDeviceShareRecord({
      shareDevices: this.selectedDevices.map(({ mac, productKey }) => ({ mac, productKey })),
      ...params,
    });
  }
}

const DeviceShare_Store_Key = 'deviceShare';

export { DeviceShare, DeviceShare_Store_Key };

export default new DeviceShare();
